# Untitled - By: Swiper_Witty - 周一 11月 22 2021

import sensor
import image
import lcd
import time
from Maix import GPIO
from machine import UART
from fpioa_manager import fm

fm.register(11,fm.fpioa.UART2_TX)
fm.register(7,fm.fpioa.UART2_RX)
uart_B = UART(UART.UART2, 9600, 8, 0, 0, timeout=1000, read_buf_len=4096)

fm.register(13,fm.fpioa.GPIO1)
fm.register(12,fm.fpioa.GPIO2)
fm.register(14,fm.fpioa.GPIO3)
LED_R = GPIO(GPIO.GPIO1,GPIO.OUT)
LED_G = GPIO(GPIO.GPIO2,GPIO.OUT)
LED_B = GPIO(GPIO.GPIO3,GPIO.OUT)

write_str = '{K210 Ready}'

clock = time.clock()
lcd.init()
sensor.reset()
sensor.set_pixformat(sensor.RGB565)
sensor.set_framesize(sensor.QVGA)
sensor.set_vflip(0)
sensor.run(1)
sensor.skip_frames(30)
time_num = 2

def LED_RGB(A = ' '):
    if A == 'r' or  A == 'R':
        LED_R.value(0)
        LED_G.value(1)
        LED_B.value(1)
    elif A == 'g' or  A == 'G':
        LED_R.value(1)
        LED_G.value(0)
        LED_B.value(1)
    elif A == 'b' or  A == 'B':
        LED_R.value(1)
        LED_G.value(1)
        LED_B.value(0)
    else:
        LED_R.value(1)
        LED_G.value(1)
        LED_B.value(1)
    return

uart_B.write(write_str)
print(write_str)
LED_RGB()
while True:
    clock.tick()
    img = sensor.snapshot()
    res = img.find_qrcodes()
    fps =clock.fps()
    if uart_B.any():
        read_data = str(uart_B.read(),'UTF-8')
        if 'Start K210' in read_data:
            time_num = 1
            print('K210 Ready')
            LED_RGB('G')
        elif 'Stop K210' in read_data:
            time_num = 2
            print('K210 Stop')
            LED_RGB('R')
        else:
            print('UART2 EEROR\r\n')
            uart_B.write('UART2 EEROR\r\n')

    if len(res) > 0:
        img.draw_string(2, 2, res[0].payload(), color=(0,128,0), scale=2)
        write_str = res[0].payload()
        print(write_str+'}')
        if time_num == 1:
            time_num = 2
            uart_B.write(write_str+'}')
            LED_RGB('B')
            time.sleep_ms(500)
    lcd.display(img)


